// JavaScript Document

const VERSION = "Version = 2.0.0";

function loadpy(url, postInfo, callback, syn) {
    "use strict";
    if (!arguments[3]) syn = true; 
    var fdata = new FormData();
    for (var key in postInfo) {
        fdata.append(key, postInfo[key]);
    }
    var xmlhttp = new XMLHttpRequest(); //暂时先不添加对ie6及以下的支持了
    //url = encodeURI(url);
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            if (callback) { //没有callback函数的话，就相当于只发送命令而不接收返回值
                
                callback(decodeURIComponent(xmlhttp.responseText));
            }
        }
    };
    xmlhttp.open("POST", "" + url, syn);
    xmlhttp.send(fdata);
}

var cli;//websocketsclient
const starbdz = Vue.createApp({
    name: "starbdz",
    data() {
        return {
            screen:"载入中...",
			working:false
        }
    },
    methods: {
        setScreen(str) {
			this.screen = str;
        },
		res(resp){
			if(resp.type == "screen"){
				this.setScreen(resp.msg);
			}
			else if(resp.type == "completed"){
				this.working = false;
			}
		},
		send(msg,type="key"){
			cli.send(JSON.stringify({
				type:type,
				msg:msg
			}));
		},
        start(){
            loadpy("/deviceStart",{});
        },
        stop(){
            loadpy("/deviceStop",{});
        },
    },
    mounted() {
        window.SS = this.setScreen;
        window.handleResponse = this.res;
    }
});
var SS;
var handleResponse;

//////////////////////////////////////////////////////////////////////////////////
jQuery(document).ready(function () {
    cli = new WebSocket('ws://' + window.location.hostname + ':8525/');
    starbdz.mount("#starbdz");
    cli.onopen = function () {
		//document.getElementById("screen").innerHTML="欢迎来到星尘测试系统!";
		
    };
    
    cli.onmessage = function (msg) {
        handleResponse(JSON.parse(msg.data));
    }

    cli.onerror = function () {
        SS("Link Error!\nTry Again!");
    }

});
